/**
 * Notes: 工作量模块控制器
 * Ver : CCMiniCloud Framework 2.0.1 ALL RIGHTS RESERVED BY cclinux0730 (wechat)
 * Date: 2024-06-12 04:00:00 
 */

const BaseProjectController = require('./base_project_controller.js');
const FlowService = require('../service/flow_service.js');
const contentCheck = require('../../../framework/validate/content_check.js');
const timeUtil = require('../../../framework/helpers/time_util.js');

class FlowController extends BaseProjectController {

	async getFlowDetail() {
		// 数据校验 
		let rules = {
			id: 'id|must',
		};

		// 取得数据
		let input = this.validateData(rules);

		let service = new FlowService();
		let flow = await service.getFlowDetail(this._userId, input.id);

		if (flow) {
			for (let k = 0; k < flow.FLOW_LIST.length; k++) {
				flow.FLOW_LIST[k].time = timeUtil.timestamp2Time(flow.FLOW_LIST[k].time, 'Y-M-D h:m');
			}
			flow.FLOW_ADD_TIME = timeUtil.timestamp2Time(flow.FLOW_ADD_TIME, 'Y-M-D h:m');
		}

		return flow;
	}

	async viewFlow() {
		// 数据校验
		let rules = {
			id: 'string|min:1|max:50|name=流程编号',
		};

		// 取得数据
		let input = this.validateData(rules);

		try {
			console.log('[Flow Controller] 查看流程，输入数据:', JSON.stringify(input));

			if (!input || !input.id) {
				// 尝试从请求体获取ID
				const body = this._request.body;
				if (body && body.id) {
					input = input || {};
					input.id = body.id;
					console.log('[Flow Controller] 从请求体获取ID:', input.id);
				} else {
					console.error('[Flow Controller] 未提供有效的流程ID');
					this.AppError('未提供有效的流程ID');
				}
			}

			// 检查ID格式
			if (input.id && (!typeof input.id === 'string' || input.id.length < 1)) {
				console.error('[Flow Controller] 流程ID格式无效:', input.id);
				this.AppError('流程ID格式无效');
			}

			console.log('[Flow Controller] 开始查询流程，ID:', input.id);
			let service = new FlowService();
			let flow = await service.viewFlow(this._userId, input);

			if (!flow) {
				console.error('[Flow Controller] 未找到流程数据，ID:', input.id);
				this.AppError('未找到流程数据，请检查流程ID是否正确');
				return null;
			}

			// 格式化时间
			if (flow.FLOW_LIST && Array.isArray(flow.FLOW_LIST)) {
				for (let k = 0; k < flow.FLOW_LIST.length; k++) {
					if (flow.FLOW_LIST[k].time) {
						flow.FLOW_LIST[k].time = timeUtil.timestamp2Time(flow.FLOW_LIST[k].time, 'Y-M-D h:m');
					}
				}
			}
			
			if (flow.FLOW_ADD_TIME) {
				flow.FLOW_ADD_TIME = timeUtil.timestamp2Time(flow.FLOW_ADD_TIME, 'Y-M-D h:m');
			}
			
			console.log('[Flow Controller] 流程查询成功，ID:', flow._id, '标题:', flow.FLOW_TITLE);
			return flow;
		} catch (err) {
			console.error('[Flow Controller] 查看流程出错:', err);
			throw err;
		}
	}

	async insertFlow() {
		// 数据校验 
		let rules = {
			cateId: 'string|min:1|max:50|name=分类ID',
			cateName: 'string|min:1|max:50|name=分类名称',
			depts: 'array|name=部门信息',
			forms: 'array|name=表单信息'
		};

		// 取得数据
		let input = this.validateData(rules);
		
		console.log('[Flow Controller] 插入流程数据:', JSON.stringify(input));

		// 确保forms是数组
		if (!Array.isArray(input.forms)) {
			console.log('[Flow Controller] 表单数据格式错误:', typeof input.forms);
			if (input.forms && typeof input.forms === 'object') {
				// 尝试修复
				input.forms = Object.values(input.forms);
				console.log('[Flow Controller] 修复后的表单数据:', JSON.stringify(input.forms));
			} else {
				this.AppError('表单数据格式错误');
			}
		}

		try {
			// 内容审核
			await contentCheck.checkTextMultiClient(input);

			let service = new FlowService();
			let result = await service.insertFlow(this._userId, input);

			if (!result || !result.id) {
				console.error('[Flow Controller] 插入流程失败，未返回有效ID');
				this.AppError('审批流程创建失败');
			}

			console.log('[Flow Controller] 插入流程成功，ID:', result.id);
			return result;
		} catch (err) {
			console.error('[Flow Controller] 插入流程错误:', err);
			throw err;
		}
	}

	async editFlow() {
		try {
			console.log('[Flow Controller] 收到editFlow请求');
			
			// 数据校验
			let rules = {
				id: 'string|min:1|max:50|name=流程ID',
				forms: 'array|name=表单数据'
			};

			// 取得数据
			let input = this.validateData(rules);
			
			console.log('[Flow Controller] 处理流程修改，用户ID:', this._userId, '流程ID:', input.id);

			// 内容审核
			await contentCheck.checkTextMultiClient(input);

			let service = new FlowService();
			let result = await service.editFlow(this._userId, input);
			
			console.log('[Flow Controller] 流程修改成功');
			return result;
		} catch (err) {
			console.error('[Flow Controller] 流程修改错误:', err);
			throw err;
		}
	}

	async stepFlow() {

		let rules = {
		 
		};

		// 取得数据
		let input = this.validateData(rules);

		// 内容审核
		await contentCheck.checkTextMultiClient(input);

		let service = new FlowService();
		let result = service.stepFlow(this._userId, input);

		return result;
	}

	async updateFlowForms() {
		try {
			console.log('[Flow Controller] 收到updateFlowForms请求');
			
			// 数据校验
			let rules = {
				id: 'string|min:1|max:50|name=流程ID',
				hasImageForms: 'array|name=图片表单'
			};

			// 取得数据
			let input = this.validateData(rules);
			
			// 添加用户ID到输入参数
			input.userId = this._userId;
			
			console.log('[Flow Controller] 处理表单更新，用户ID:', this._userId, '流程ID:', input.id);

			// 内容审核
			await contentCheck.checkTextMultiClient(input);

			let service = new FlowService();
			let result = await service.updateFlowForms(input);
			
			console.log('[Flow Controller] 表单更新成功');
			return result;
		} catch (err) {
			console.error('[Flow Controller] 表单更新错误:', err);
			throw err;
		}
	}
  

	/** 删除 */
	async delFlow() {

		// 数据校验
		let rules = {
			id: 'must|id',
		};

		// 取得数据
		let input = this.validateData(rules);

		let service = new FlowService();
		await service.delFlow(this._userId, input.id);

	}

	/** 我的申请列表 */
	async getMyFlowList() {
		try {
			console.log('[Flow Controller] 获取我的申请列表');
			
			// 数据校验
			let rules = {
				search: 'string|optional',
				sortType: 'string|optional',
				sortVal: 'string|optional',
				orderBy: 'object|optional',
				page: 'must|int|default=1',
				size: 'must|int|default=10',
				isTotal: 'bool|optional',
				oldTotal: 'int|optional',
			};

			// 取得数据
			let input = this.validateData(rules);
			
			console.log('[Flow Controller] 处理我的申请列表查询，用户ID:', this._userId, '查询条件:', JSON.stringify(input));

			let service = new FlowService();
			let result = await service.getMyFlowList(this._userId, input);

			// 数据格式化
			if (result && result.list) {
				result.list.forEach(item => {
					if (item.FLOW_ADD_TIME) 
						item.FLOW_ADD_TIME = timeUtil.timestamp2Time(item.FLOW_ADD_TIME, 'Y-M-D h:m');
				});
			}
			
			console.log('[Flow Controller] 查询成功，返回记录数:', result?.list?.length || 0);
			return result;
		} catch (err) {
			console.error('[Flow Controller] 获取我的申请列表出错:', err);
			throw err;
		}
	}

	// 待我审批
	async getMyCheckingList() {

		// 数据校验
		let rules = {
			search: 'string|min:1|max:30|name=搜索条件',
			sortType: 'string|name=搜索类型',
			sortVal: 'name=搜索类型值',
			orderBy: 'object|name=排序',
			page: 'must|int|default=1',
			size: 'int',
			isTotal: 'bool',
			oldTotal: 'int',
		};

		// 取得数据
		let input = this.validateData(rules);

		let service = new FlowService();
		let result = await service.getMyCheckingList(this._userId, input);

		// 数据格式化
		let list = result.list;

		for (let k = 0; k < list.length; k++) {
			list[k].FLOW_ADD_TIME = timeUtil.timestamp2Time(list[k].FLOW_ADD_TIME, 'Y-M-D h:m'); 
		}

		result.list = list;

		return result;

	}

	// 我已审批
	async getMyCheckedList() {

		// 数据校验
		let rules = {
			search: 'string|min:1|max:30|name=搜索条件',
			sortType: 'string|name=搜索类型',
			sortVal: 'name=搜索类型值',
			orderBy: 'object|name=排序',
			page: 'must|int|default=1',
			size: 'int',
			isTotal: 'bool',
			oldTotal: 'int',
		};

		// 取得数据
		let input = this.validateData(rules);

		let service = new FlowService();
		let result = await service.getMyCheckedList(this._userId, input);

		// 数据格式化
		let list = result.list;

		for (let k = 0; k < list.length; k++) {
			list[k].FLOW_ADD_TIME = timeUtil.timestamp2Time(list[k].FLOW_ADD_TIME, 'Y-M-D h:m'); 
		}

		result.list = list;

		return result;

	}

	/**
	 * 获取流程详情
	 */
	async detail() {
		try {
			console.log('[Flow Controller] 获取流程详情');
			
			// 数据校验
			let rules = {
				id: 'string|min:1|max:50|name=流程ID'
			};

			// 取得数据
			let input = this.validateData(rules);
			
			console.log('[Flow Controller] 获取流程详情，ID:', input.id);

			let service = new FlowService();
			let flow = await service.getFlowDetail(this._userId, input.id);
			
			if (!flow) {
				console.error('[Flow Controller] 未找到流程数据');
				this.AppError('未找到流程');
				return null;
			}
			
			// 确保所有必要字段存在
			if (!flow.FLOW_STEP) {
				flow.FLOW_STEP = [];
				console.warn('[Flow Controller] FLOW_STEP字段不存在，初始化为空数组');
			}
			
			// 确保用户信息字段存在
			if (!flow.FLOW_USER) {
				flow.FLOW_USER = flow.FLOW_USER_NAME || '';
				console.warn('[Flow Controller] FLOW_USER字段不存在，初始化为空字符串');
			}
			
			// 确保标题字段存在
			if (!flow.FLOW_TITLE) {
				flow.FLOW_TITLE = flow.FLOW_OBJ?.title || flow.FLOW_CATE_NAME || '';
				console.warn('[Flow Controller] FLOW_TITLE字段不存在，从其他字段获取');
			}
			
			// 确保FLOW_OBJ字段存在
			if (!flow.FLOW_OBJ) {
				flow.FLOW_OBJ = {};
				console.warn('[Flow Controller] FLOW_OBJ对象不存在，初始化为空对象');
			}
			
			// 确保URL和内容字段存在
			flow.FLOW_OBJ_URL = flow.FLOW_OBJ_URL || '';
			flow.FLOW_OBJ_CONTENT = flow.FLOW_OBJ_CONTENT || '';
			
			// 确保时间字段存在
			flow.FLOW_TITLE_TIME = flow.FLOW_TITLE_TIME || flow.FLOW_ADD_TIME || '';
			
			// 格式化时间
			if (flow.FLOW_ADD_TIME) {
				flow.FLOW_ADD_TIME = timeUtil.timestamp2Time(flow.FLOW_ADD_TIME, 'Y-M-D h:m');
			}
			
			console.log('[Flow Controller] 流程详情获取成功，ID:', flow._id);
			return flow;
		} catch (err) {
			console.error('[Flow Controller] 获取流程详情错误:', err);
			throw err;
		}
	}

}

module.exports = FlowController;